package com.cyc.controller;

import com.alibaba.fastjson.JSON;
import com.cyc.entity.CartItem;
import com.cyc.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Autowired
    ServletContext servletContext;

    @Autowired
    private CartService cartService;

    @RequestMapping(value = "/add")
    @ResponseBody
    public String add(HttpServletRequest request, HttpServletResponse response,Integer id,Integer num){
        Map<String, Object> map=new HashMap<>();
        int i = cartService.addCareService(request, response, id, num);
        if (i>0){
            map.put("msg","添加购物车成功");
        }
        return JSON.toJSONString(map);
    }

    @RequestMapping("/get")
    public String get(HttpServletRequest request, Model model){
        List<CartItem> list = cartService.getCartFromCookie(request);
        model.addAttribute("shopList",list);
        return "shopping";
    }

    @RequestMapping("/del")
    @ResponseBody
    public String del(Integer id,HttpServletRequest request){
        Map<String, Object> map=new HashMap<>();
//        List<CartItem> list = (List<CartItem>) request.getSession().getAttribute("shop");
        List<CartItem> list = (List<CartItem>)servletContext.getAttribute("shop");
        for (CartItem item:list){
            if (item.getId().equals(id)){
                list.remove(item);
                break;
            }
        }
        request.getSession().setAttribute("shop",list);
        map.put("msg","删除成功");
        return JSON.toJSONString(map);
    }
}
